package cn.tedu.egweibo2.controller;

import cn.tedu.egweibo2.mapper.UserMapper;
import cn.tedu.egweibo2.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo2.pojo.dto.UserRegDTO;
import cn.tedu.egweibo2.pojo.entity.User;
import cn.tedu.egweibo2.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/user/")
@Api(tags = "用户模块")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("注册功能")
    @PostMapping("reg")
    public int insertReg(@RequestBody UserRegDTO userRegDTO){
        UserVO userVO=userMapper.selectByUsername(userRegDTO.getUsername());
        if(userVO!=null){
            return 2;
        }
        User user=new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertReg(user);
        return 1;
    }
    @ApiOperation("登录功能")
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        UserVO userVO=userMapper.selectByUsername(userLoginDTO.getUsername());
        log.debug("userVO="+userVO);
        if(userVO!=null){
            if(userVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userVO);
                return 1;
            }
            return 2;
        }
        return 3;
    }
}
